import { Injectable, Inject } from '@angular/core';
import { HttpClient, HttpResponse, HttpHeaders } from '@angular/common/http';
import { Event } from './equipment.model';
import { Observable, of, Subject } from 'rxjs';
import { catchError, filter, map } from 'rxjs/operators';
import { ConfigService } from 'app/config/config.service';
import { EQUIPMENT_API_URL, ALARM_API_URL } from 'app/app.constants';

export const httpOptions: Object = {
    headers: new HttpHeaders({
        'Content-Type': 'application/json'
        // 'Authorization': 'my-auth-token',
        // Accept: 'text/plain'
    })
    // responseType: 'text'
};

@Injectable({
    providedIn: 'root'
})
export class EquipmentService {
    private apiUrl_user_online = this.config.apiUrl.user;
    private apiUrl_alarm_online = this.config.apiUrl.alarm;
    private apiUrl_equip_online = this.config.apiUrl.equipment;
    public apiUrl_equip_export = this.config.apiUrl.equipment + '/equipMgt/equip/uploadImg';
    public apiUrl_equip_uploadChunkImg = this.config.apiUrl.equipment + '/equipMgt/equip/uploadChunkImg';
    private apiUrl_equip_vmsErr = this.config.apiUrl.vmsErr;
    // public apiUrl_equip_export = 'http://192.168.0.56:9575/equipMgt/equip/uploadImg';
    // private apiUrl_alarm_online = ALARM_API_URL;
    // private apiUrl_equip_online = EQUIPMENT_API_URL;

    public events: Event[] = [];

    constructor(private http: HttpClient, private config: ConfigService) {}

    getEquipmentList(params): Observable<any> {
        const url = `${this.apiUrl_equip_online}/equipMgt/equip/getDeviceInfoByPage`;
        return this.http.post<any>(url, params, httpOptions);
    }

    getAllDeviceStatusStatistics(): Observable<any> {
        const url = `${this.apiUrl_equip_online}/equipMgt/equip/getAllDeviceStatusStatistics`;
        return this.http.get<any>(url);
    }

    // 删除多余的图片
    deleteImgByUrl(deleteUrl): Observable<any> {
        const url = `${this.apiUrl_equip_online}/equipMgt/equip/deleteImgByUrl?url=${deleteUrl}`;
        return this.http.get<any>(url);
    }

    // 获取用户列表
    getAllUser(param): Observable<any> {
        // const url = `${this.apiUrl_equip_online}/userMgt/user/getAllUser`;
        return this.http.post<any>(this.apiUrl_user_online + '/userMgt/user/getAllUserInfoByPage', param);
    }

    postCreateDevice(data, header): Observable<any> {
        let headers = new HttpHeaders();
        headers = headers.append('Content-Type', 'application/json');
        headers = headers.append('isForce', header.isFource);
        headers = headers.append('zoneId', header.zoneId);
        const imgUrl = [];
        if (data.url) {
            data.url.forEach(item => {
                if (item) {
                    imgUrl.push(item);
                }
            });
        }
        const device = {
            blackList: new Date().getTime() + '',
            connectionStatus: null,
            constructionPerson: data.constructionPerson,
            constructionUnit: data.constructionUnit,
            deviceName: null,
            direction: data.direction,
            eqtId: data.id,
            eqtType: data.type,
            installDate: new Date(data.installDate).getTime() + '',
            ipAddr: data.ip,
            latitude: data.latitude,
            longitude: data.longitude,
            netDate: new Date(data.nextDate).getTime() + '',
            roadName: data.roadName,
            supervisionEngineers: data.supervision,
            url: imgUrl,
            workStatus: 'OK',
            zoneId: data.zoneID
        };
        const url = `${this.apiUrl_equip_online}/equipMgt/equip/createDevice`;
        return this.http.post<any>(url, JSON.stringify(device), { headers });
    }

    postUpdateDevice(data, header): Observable<any> {
        let headers = new HttpHeaders();
        headers = headers.append('Content-Type', 'application/json');
        headers = headers.append('isForce', header.isFource);
        headers = headers.append('zoneId', header.zoneId);
        let temp = null;
        if (typeof data.url === 'string') {
            temp = data.url.split(',');
        } else {
            temp = data.url;
        }
        const imgUrl = [];
        temp.forEach(item => {
            if (item && item !== 'null') {
                imgUrl.push(item);
            }
        });
        const device = {
            blackList: new Date().getTime() + '',
            constructionPerson: data.constructionPerson,
            constructionUnit: data.constructionUnit,
            deviceName: null,
            direction: data.direction,
            eqtId: data.id,
            eqtType: data.type,
            installDate: new Date(data.installDate).getTime() + '',
            ipAddr: data.ip,
            latitude: data.latitude,
            longitude: data.longitude,
            netDate: new Date(data.nextDate).getTime() + '',
            roadName: data.roadName,
            supervisionEngineers: data.supervision,
            url: imgUrl,
            workStatus: 'OK',
            zoneId: data.zoneID,
            status: data.status,
            connectionStatus: data.connectionStatus
        };
        const url = `${this.apiUrl_equip_online}/equipMgt/equip/updateDevice`;
        return this.http.post<any>(url, JSON.stringify(device), { headers });
    }

    deleteDevices(fieldIds, header): Observable<any> {
        let headers = new HttpHeaders();
        headers = headers.append('Content-Type', 'application/json');
        headers = headers.append('isForce', header.isFource);
        headers = headers.append('zoneId', header.zoneId);
        const url = `${this.apiUrl_equip_online}/equipMgt/equip/deleteDevices`;
        return this.http.get<any>(url, { params: { fieldIds }, responseType: 'text' as 'json', headers });
    }

    getAlarmList(params): Observable<any> {
        const url = `${this.apiUrl_alarm_online}/vnqnalarmmgt/techAlarm/get`;
        return this.http.post<any>(url, params, httpOptions);
    }

    getVmsErr(deviceId): Observable<any> {
        const url = `${this.apiUrl_equip_vmsErr}/vnqnoperationlog/log/getVMSError`;
        return this.http.get<any>(url, { params: { deviceId }, responseType: 'text' as 'json' });
    }

    /*putAckAlarm(data, header): Observable<any> {
        const param = {
            alarmId: data.alarmId,
            zoneID: data.zoneID
        };
        let headers = new HttpHeaders();
        headers = headers.append('Content-Type', 'application/json');
        headers = headers.append('isForce', header.isFource);
        headers = headers.append('zoneId', header.zoneId);
        const url = `${this.apiUrl_alarm_online}/vnqnalarmmgt/techAlarm/ack`;
        return this.http.get<any>(url, { params: param, headers });
    }*/

    putAckAlarm(data, header): Observable<any> {
        const param = [
            {
                alarmId: data.alarmId,
                zoneID: data.zoneID
            }
        ];
        let headers = new HttpHeaders();
        headers = headers.append('Content-Type', 'application/json');
        headers = headers.append('isForce', header.isForce);
        headers = headers.append('zoneId', header.zoneId);
        const url = `${this.apiUrl_alarm_online}/vnqnalarmmgt/techAlarm/ackAll`;
        return this.http.put<any>(url, param, { headers });
    }

    putFalseAlarm(data, header): Observable<any> {
        const param = [
            {
                alarmId: data.alarmId,
                zoneID: data.zoneID
            }
        ];
        let headers = new HttpHeaders();
        headers = headers.append('Content-Type', 'application/json');
        headers = headers.append('isForce', header.isForce);
        headers = headers.append('zoneId', header.zoneId);

        const url = `${this.apiUrl_alarm_online}/vnqnalarmmgt/techAlarm/clearAll`;
        return this.http.put<any>(url, param, { headers });
    }

    getAlarmHis(params): Observable<any> {
        const url = `${this.apiUrl_alarm_online}/vnqnalarmmgt/techAlarm/getHist`;
        return this.http.post<any>(url, params, httpOptions);
    }

    // type  0:转换为时间戳， 1:转换为显示时间
    changeDate(dates, type) {
        if (!dates) {
            return null;
        }
        let dated;
        switch (type) {
            case 0: {
                dated = new Date(dates).getTime();
                break;
            }
            case 1: {
                const temp = new Date(dates);
                const year = temp.getFullYear();
                const month = temp.getMonth() + 1 >= 10 ? temp.getMonth() + 1 : '0' + (temp.getMonth() + 1);
                const day = temp.getDate() >= 10 ? temp.getDate() : '0' + temp.getDate();
                const hours = temp.getHours() >= 10 ? temp.getHours() : '0' + temp.getHours();
                const min = temp.getMinutes() >= 10 ? temp.getMinutes() : '0' + temp.getMinutes();
                // dated = temp.getFullYear() + '-' + (temp.getMonth() + 1) + '-' + temp.getDate() + ' ' + temp.getHours() + ':' + temp.getMinutes();
                dated = year + '/' + month + '/' + day + ' ' + hours + ':' + min;
                break;
            }
        }
        return dated;
    }
}
